<template>
  <el-dialog v-model="model" @close="closedDialog">
    <el-form
      ref="jobTriggerFormRef"
      :model="form"
      label-width="120px"
      :rules="rules"
    >
      <el-row>
        <!-- 是否立即开始 -->
        <el-col :span="24">
          <el-form-item :label="$t('jobTrigger.startNow')" prop="startNow">
            <el-radio-group v-model="form.startNow">
              <el-radio
                v-for="item in Dict.jobTriggerDict.values"
                :key="item.key"
                :value="item.key"
              >
                {{ item.value }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!-- 开始时间 -->
        <el-col :span="24" v-if="form.startNow == false">
          <el-form-item :label="$t('jobTrigger.startDate')" prop="startDate">
            <el-date-picker
              v-model="form.startDate"
              type="datetime"
              :placeholder="$t('jobTrigger.startDateRequired')"
              format="YYYY-MM-DD HH:mm"
              clearable
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <!-- 是否自定义 -->
        <el-col :span="24">
          <el-form-item :label="$t('jobTrigger.isCustom')" prop="isCustom">
            <el-radio-group v-model="form.isCustom">
              <el-radio
                v-for="item in Dict.jobTriggerDict.values"
                :key="item.key"
                :value="item.key"
              >
                {{ item.value }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!-- cron表达式 -->
        <el-col :span="24" v-if="form.isCustom == false">
          <el-form-item :label="$t('jobTrigger.cron')" prop="cron">
            <el-input
              v-model="form.cron"
              :placeholder="$t('jobTrigger.cronRequired')"
              :disabled="form.isCustom == false"
            >
            </el-input>
          </el-form-item>
          <div>
            <Vue3Cron
              v-model:value="form.cron"
              @cronstrueChange="cronstrueChange"
            />
          </div>
        </el-col>
         <!-- cron表达式 -->
        <el-col :span="24" v-if="form.isCustom">
          <el-form-item :label="$t('jobTrigger.cron')" prop="cron">
            <el-input
              v-model="form.cron"
              :placeholder="$t('jobTrigger.cronRequired')"
              @change="cronstrueChange"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <!-- cron中文描述 -->
        <el-col :span="24">
          <el-form-item :label="$t('jobTrigger.cronName')" prop="cronName">
            <el-input
              v-model="form.cronName"
              type="textarea"
              :autosize="{ minRows: 3 }"
              maxlength="200"
              show-word-limit
              :placeholder="$t('jobTrigger.cronNameRequired')"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closedDialog">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, type PropType, getCurrentInstance } from "vue";
import { type FormInstance, type FormRules, ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import type {
  JobTriggerKey,
  JobTriggerFormReq,
  JobTriggerCreateReq,
  JobTriggerUpdateReq,
} from "@/api/jobs/job-trigger/types";
import { jobTriggerApi } from "@/api/jobs/job-trigger/index";
import { Dict } from "@/api/jobs/index";
import cronstrue from "cronstrue";
import "cronstrue/locales/zh_CN";
const jobTriggerFormRef = ref<FormInstance>();
const { proxy } = getCurrentInstance() as any;
const model = defineModel<boolean>();
const emits = defineEmits(["refresh"]);
const props = defineProps({
  // 任务主键ID(jobName)
  jobKey: {
    type: String,
    default: () => "",
  },
  // 任务触发器主键ID
  triggerKey: {
    type: Object as PropType<JobTriggerKey>,
    default: () => {},
  },
});

// 表单数据
let form: JobTriggerFormReq = reactive<JobTriggerFormReq>({
  requestId: Math.random() * 10 + "",
  updateMask: "startDate,cron,startNow,isCustom,cronName",
  startNow: false,
  isCustom: false,
});
// cron表达式转换
const cronstrueChange = () => {
  if (form.cron) {
    const cronStrue = cronstrue.toString(form.cron as string, {
      locale: "zh_CN",
    });
    form.cronName = cronStrue;
  }
};
// 表单验证规则
const rules = reactive<FormRules<JobTriggerFormReq>>({
  startDate: [
    {
      required: true,
      message: t("jobTrigger.startDateRequired"),
      trigger: "change",
    },
  ],
  cron: [
    {
      required: true,
      pattern:
        "^\\s*($|#|\\w+\\s*=|(\\?|\\*|(?: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T|SUN)(?:(?:-)(?:MON|TUE|WED|THU|FRI|SAT|SUN))?)*)(|\\s)+(\\?|\\*|(?:|\\d{4})(?:(?:-|\\/|\\,)(?:|\\d{4}))?(?:,(?:|\\d{4})(?:(?:-|\\/|\\,)(?:|\\d{4}))?)*))$",
      message: t("jobTrigger.cronRequireds"),
      trigger: "change",
    },
  ],
  cronName: [
    {
      required: true,
      message: t("jobTrigger.cronNameRequired"),
      trigger: "change",
    },
  ],
});

// 做编辑功能时使用开始
const keys = Object.keys(props.triggerKey);
const update = ref(keys.length >= 1);
if (update.value) {
  jobTriggerApi
    .findById({ triggerId: props.triggerKey.triggerId })
    .then(({ data }) => {
      Object.assign(form, data);
      cronstrueChange();
    });
}
// 做编辑功能时使用结束
// 提交表单校验
const submitForm = async () => {
  await jobTriggerFormRef.value?.validate((valid) => {
    if (valid) {
      // 开始时间格式化时间
      form.startDate = proxy.$moment.formatDate(form.startDate);
      /// 任务主键ID(jobName)
      form.jobName = props.jobKey;
      if (update.value) {
        jobTriggerApi.update(form as JobTriggerUpdateReq).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
          }
        });
      } else {
        jobTriggerApi.create(form as JobTriggerCreateReq).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
          }
        });
      }
    }
  });
};

// 关闭弹框
function closedDialog() {
  if (model.value) {
    model.value = false;
  }
}
</script>
